package com.itboye.sunsun.person.ui;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import com.itboye.sunsun.R;
import com.itboye.sunsun.adapter.CustomListViewAdapter;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.beans.CustomBean;
import com.itboye.sunsun.beans.OrderBean;
import com.itboye.sunsun.beans.OrderBean.DetailBean;
import com.itboye.sunsun.beans.OrderBean.InnerDetailBean;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.custome.XListView;
import com.itboye.sunsun.custome.XListView.IXListViewListener;
import com.itboye.sunsun.message.ui.MessageActivity;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.person.adapter.CompleteActivityAdapter;
import com.itboye.sunsun.person.fragments.PayActivity;
import com.itboye.sunsun.support.BaseActivity;
import com.itboye.sunsun.utils.DebugLog;
import com.itboye.sunsun.utils.DoubleParse;
import com.itboye.sunsun.utils.SPUtils;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class CustomActivity extends BaseActivity implements OnClickListener, OnItemClickListener {

	private XListView xListView;
	private ImageView message;
	private CustomListViewAdapter adapter;
	private RelativeLayout backrela;
	private RelativeLayout gonerela;
	private int pageNum = 1;
	private List<InnerDetailBean> dataList = new ArrayList<OrderBean.InnerDetailBean>();
	private Map<String, DetailBean> map;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_custom);
		adapter = new CustomListViewAdapter(App.ctx, dataList);
		initView();

	}

	public void initView() {

		xListView.setPullRefreshEnable(true);
		xListView.setPullLoadEnable(true);
		xListView.setOnItemClickListener(this);
		xListView.setXListViewListener(new IXListViewListener() {

			@Override
			public void onRefresh() {
				pulldown();

			}

			@Override
			public void onLoadMore() {
				pullup();

			}
		});
		xListView.setAdapter(adapter);
		pulldown();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.backrela:
			this.finish();
			break;
		case R.id.message:
			Intent intent = new Intent(this, MessageActivity.class);
			startActivity(intent);

		default:
			break;
		}

	}

	public void pulldown() {
		pageNum = 1;
		MyJsonRequest.Builder<OrderBean> builder = new MyJsonRequest.Builder<OrderBean>()
				.param("uid", (String) SPUtils.get(App.ctx, null, SPContants.USER_ID, "")).apiVer("100")
				.param("curpage", "" + pageNum).param("pagesize", "10").param("status", 5).typeKey("BY_Orders_query")
				.requestListener(new XRequestListener<OrderBean>() {

					@Override
					public void onResponse(OrderBean orderBean) {

						onPullDownFinish(adapter, xListView, orderBean);
						pageNum++;
						xListView.stopRefresh();

					}

				}).errorListener(new XErrorListener() {

					@Override

					public void onErrorResponse(Exception exception, int code, String msg) {
						xListView.stopRefresh();
						// onPullDownError(adapter, xlistview, exception, code,
						xListView.setEmptyView(gonerela);
					}
				});

		MyJsonRequest<OrderBean> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	public void pullup() {
		MyJsonRequest.Builder<OrderBean> builder = new MyJsonRequest.Builder<OrderBean>()
				.param("uid", (String) SPUtils.get(App.ctx, null, SPContants.USER_ID, "")).apiVer("100")
				.typeKey("BY_Orders_query").param("curpage", "" + pageNum).param("pagesize", "10").param("status", 5)

				.requestListener(new XRequestListener<OrderBean>() {

					@Override
					public void onResponse(OrderBean orderBean) {
						onPullUpFinish(adapter, xListView, orderBean);
						pageNum++;
						xListView.stopLoadMore();
					}

				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code, String msg) {
						xListView.stopLoadMore();
						onPullUpError(adapter, xListView, exception, code, msg);
					}

				});

		MyJsonRequest<OrderBean> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	private void onPullDownFinish(CustomListViewAdapter adapter, XListView xListView, OrderBean orderBean) {
		dataList.clear();
		addDataToList(dataList, orderBean);
		adapter.notifyDataSetChanged();
	}

	private void addDataToList(List<InnerDetailBean> dataList2, OrderBean orderBean) {
		map = orderBean.getList();
		if (map == null) {
			return;
		}
		Set<Entry<String, DetailBean>> set = map.entrySet();
		if (set == null) {
			return;
		}
		for (Entry<String, DetailBean> entry : set) {

			int count = 0;
			double price = 0;
			if (entry == null || entry.getValue() == null || entry.getKey() == null) {
				continue;
			}
			String allprice = entry.getValue().getPrice();

			int paystatus = Integer.parseInt(entry.getValue().getPayStatus());
			int orderstatus = Integer.parseInt(entry.getValue().getOrderStatus());
			int csStatus = Integer.parseInt(entry.getValue().getCsStatus());

			// 头部Item

			InnerDetailBean detailBean1 = new InnerDetailBean();
			detailBean1.setViewType(1);
			detailBean1.setOrderCode(entry.getKey());
			detailBean1.setCount(count + "");
			detailBean1.setPrice("" + price);
			dataList.add(detailBean1);
			if (csStatus == 2) {
				detailBean1.setState("待处理");
			} else if (csStatus == 3) {
				detailBean1.setState("已处理");
			}

			List<InnerDetailBean> list = entry.getValue().get_items();
			if (list == null) {
				continue;
			}
			for (InnerDetailBean innerDetailBean : list) {
				dataList.add(innerDetailBean);
				int c = (int) DoubleParse.parse(innerDetailBean.getCount(), 0);
				count += c;
				price = price + DoubleParse.parse(innerDetailBean.getPrice(), 0) * c;
			}

			// 底部Item
			InnerDetailBean detailBean2 = new InnerDetailBean();
			detailBean2.setViewType(2);
			detailBean2.setOrderCode(entry.getKey());
			detailBean2.setCount(count + "");
			detailBean2.setPrice("" + price);
			// DebugLog.v("price", allprice);
			detailBean2.setAllprice(allprice);
			dataList.add(detailBean2);
		}

	}

	private void onPullUpFinish(CustomListViewAdapter adapter, XListView xListView, OrderBean orderBean) {
		addDataToList(dataList, orderBean);
		adapter.notifyDataSetChanged();

	}

	private void onPullUpError(CustomListViewAdapter adapter, XListView xListView, Exception exception, int code,
			String msg) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Set<Entry<String, DetailBean>> set;
		if (map == null) {
			return;
		} else {
			set = map.entrySet();
		}

		if (set == null) {
			return;
		}
		// DebugToast.show("sassasa"+dataList.get(position-1).getOrderCode(),
		// 1);

		for (Entry<String, DetailBean> entry : set) {
			if (entry == null || entry.getValue() == null || entry.getKey() == null) {
				continue;
			}

			if (position != 0) {
				if (dataList.get(position - 1).getOrderCode().equals(entry.getValue().getOrderCode())) {

					List<InnerDetailBean> listInner = entry.getValue().get_items();
					int csStatus = Integer.parseInt(entry.getValue().getCsStatus());

					if (csStatus == 3) {
						Intent intent = new Intent(App.ctx, ApplyCustomActivity.class);
						intent.putExtra("ordercode", dataList.get(position - 1).getOrderCode());
						intent.putExtra("price", dataList.get(position - 1).getPrice());
//						System.out.println("LLLLLLLLLLLLLLLLLL"+dataList.get(position - 1).getPrice());
//						Toast.makeText(App.ctx, ""+dataList.get(position - 1).getPrice(), 1).show();
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						startActivity(intent);

					}
				}
			}
			// DebugToast.show(entry.getValue().getOrderCode(), 0);
		}

	}

}
